package com.xudm.cdg.api;

import com.alibaba.fastjson2.JSONObject;
import com.xudm.cdg.entity.agent.WxyyAgentConfig;
import com.xudm.cdg.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 文心一言代理 API
 *
 * @author xudm
 */
@Service
@Slf4j
public class WxyyAgentApi {
    private final HttpClientUtil clientUtil;
    private final WxyyAgentConfig wxyyAgentConfig;

    public WxyyAgentApi(HttpClientUtil clientUtil, WxyyAgentConfig wxyyAgentConfig) {
        this.clientUtil = clientUtil;
        this.wxyyAgentConfig = wxyyAgentConfig;
    }

    public JSONObject getAnswer(String question) {
        // 通过 HttpClient 工具类发送请求获取聊天结果
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        String chatUrl = wxyyAgentConfig.getChatUrl() + "?appId=" + wxyyAgentConfig.getAppId() + "&secretKey=" + wxyyAgentConfig.getSecretKey();
        JSONObject param = new JSONObject();
        JSONObject message = new JSONObject();
        JSONObject content = new JSONObject();
        JSONObject value = new JSONObject();

        content.put("type", "text");
        value.put("showText", question);
        content.put("value", value);
        message.put("content", content);
        param.put("message", message);
        param.put("openId", wxyyAgentConfig.getOpenId());
        param.put("source", wxyyAgentConfig.getAppId());
        param.put("from", "openapi");
        log.info("请求文心一言聊天接口，请求参数：{}", param.toJSONString());
        String responseStr = clientUtil.sendPostRequest(chatUrl, param.toJSONString(), headers);
        return JSONObject.parseObject(responseStr);
    }
}
